<?php
namespace App\Admin\Controllers\ZiNiao;

use App\Admin\Ajax\ZiNiao\TasksResultsAjax;
use App\Models\ZiNiao\TasksResults;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
class TasksResultsController extends AdminController{

    protected $title = 'RPA任务结果记录';

    protected $filters = [
        'taskId' => null,
        'rpaId' => null,
        'storeName' => null,
        'siteCode' => null,
        'reportFromDate' => null,
        'reportEndDate' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['taskId'] = $this->filters['taskId'];
        $filtersBlade['rpaId'] = $this->filters['rpaId'];
        $filtersBlade['storeName'] = $this->filters['storeName'];
        $filtersBlade['siteCode'] = $this->filters['siteCode'];
        $filtersBlade['reportFromDate'] = $this->filters['reportFromDate'];
        $filtersBlade['reportEndDate'] = $this->filters['reportEndDate'];
        $filtersBlade['status'] = getOptions(TasksResults::$_status,$this->filters['status']);
        return view('ziniao.tasks-results.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = TasksResults::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'reportFromDate'){
                $query->where('reportFromDate','>=',msectime($filter));
            }
            if($field == 'reportEndDate'){
                $query->where('reportEndDate','<=',msectime($filter));
            }
            if(in_array($field,['taskId','rpaId','storeName','siteCode','fileName','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new TasksResultsAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
